package org.opencare.plugins.gdacs;

import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class TopicPublisher implements Publisher {

	protected final Log logger = LogFactory.getLog(getClass());

	private Connection connection;

	private Session session;

	private MessageProducer publisher;

	private Topic topic;

	public TopicPublisher(String borkerUrl, String topicTarget)
			throws JMSException {
		ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(
				borkerUrl);
		connection = factory.createConnection();

		session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		topic = session.createTopic(topicTarget);
		publisher = session.createProducer(topic);
		publisher.setDeliveryMode(DeliveryMode.PERSISTENT);

	}

	public void publish(String payload) throws JMSException {

		logger.info("-------------- Publishing to JMS --------------");
		logger.debug(payload);

		connection.start();
		TextMessage textMsg = session.createTextMessage();
		textMsg.setText(payload);
		publisher.send(textMsg);
		connection.stop();
		logger.info("-------------- End Published --------------");
	}
}
